<template>
  <div class="user-regis-card-wrapper">
    <i
      class="back-to-login iconfont icon-arrow-left-bold"
      @click="$emit('toLog')"
    ></i>

    <i class="iconfont icon-cancel" @click="$emit('exit')"></i>

    <h2>找回密码</h2>

    <ul class="input-info-list">
      <li v-for="(item, idx) in infos" :key="idx">
        <component
          :is="idx === 1 || idx === 2 ? 'PasswordInput' : 'BaseInput'"
          :placeholder="item.placeholder"
          :value="(inputs as any)[idx]"
          @change="renewInput($event.target, item.key)"
          class="info-input"
        />
        <i class="iconfont icon-warning signal" v-show="ifError[idx].sign"></i>
        <p
          class="sig-message"
          v-show="ifError[idx].sign && ifError[idx].message"
        >
          {{ ifError[idx].message }}
        </p>
      </li>
    </ul>

    <div class="verification">
      <BaseInput
        class="veri-input"
        placeholder="请输入验证码"
        value=""
        @change="renewInput($event.target as HTMLInputElement, 'verification')"
      ></BaseInput>

      <button
        class="send-veri"
        @click="sendVeri"
        :class="{ sendAble: !resendCount, sendDisable: resendCount }"
      >
        {{ veriMsg }}
      </button>
    </div>

    <button class="regis-button" @click="changePwd" ref="submitBtn">
      更改密码
    </button>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import BaseInput from '../utils/Input/BaseInput.vue'
import PasswordInput from '../utils/Input/PasswordInput.vue'
import { post } from '@/utils/request'
import { show } from '@/utils/popup'

let inputs = reactive({
  account: '',
  newpwd: '',
  newpwdConfirm: '',
  verification: '',
})
let infos = reactive([
  {
    key: 'account',
    placeholder: '请输入用户名或邮箱',
  },
  {
    key: 'newpwd',
    placeholder: '请输入新密码',
  },
  {
    key: 'newpwdConfirm',
    placeholder: '请再次输入新密码',
  },
])
let ifError = reactive(
  Array.from(new Array(4), () => ({
    sign: false,
    message: '',
  }))
)
let ifShowPwd = ref(false)
let ifShowPwdCon = ref(false)
let resendCount = ref(0)

let veriMsg = computed(() => {
  if (!resendCount.value) return '发送验证码'
  else return `再次发送 ${resendCount.value}s`
})

function checkAccount(account: string) {
  if (!account.includes('@')) {
    if (account.length < 6 || account.length > 18) {
      ifError[0].sign = true
      ifError[0].message = '用户名长度必须为6-18位'
      return true
    } else if (/[^a-zA-Z0-9-_]/.test(account)) {
      ifError[0].sign = true
      ifError[0].message = '用户名只能包含字母，数字，-(连字符)和_(下划线)'
      return true
    }
  } else {
    if (
      !/^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+(\.([a-zA-Z]{2,4}))+$/.test(
        account
      )
    ) {
      ifError[0].sign = true
      ifError[0].message = '邮箱格式不正确'
      return true
    }
  }
  ifError[0].sign = false
  ifError[0].message = ''
}

function checkPassword(password: string) {
  if (!(/[a-zA-Z]/.test(password) && /[0-9]/.test(password))) {
    ifError[1].sign = true
    ifError[1].message = '密码至少包含一个字母和一个数字'
    return true
  } else if (password.length < 6) {
    ifError[1].sign = true
    ifError[1].message = '密码长度至少六位'
    return true
  } else {
    ifError[1].sign = false
    return false
  }
}

function checkPasswordConfirm(p1: string, p2: string) {
  if (p1 !== p2) {
    ifError[2].sign = ifError[1].sign = true
    ifError[1].message = ''
    ifError[2].message = '两次输入密码不一致'
    return true
  } else {
    ifError[2].sign = ifError[1].sign = false
    return false
  }
}

function sendVeri() {
  if (resendCount.value) return
  if (checkAccount(inputs.account)) {
    show('请填写用户名或邮箱')
    return
  }
  post('findpwd/sendveri', {
    account: inputs.account,
  })
    .then((ret) => {
      show('请查收邮箱')
    })
    .catch(() => {
      show('邮箱发送失败')
    })
  resendCount.value = 60
  let intervalId = setInterval(() => {
    resendCount.value--
    if (!resendCount.value) clearInterval(intervalId)
  }, 1000)
}

function renewInput(el: HTMLInputElement, key: string) {
  ;(inputs as any)[key] = el.value
  console.log('register card inputs: ', inputs)
  checkFormat(key)
}

function changePwd() {
  if (ifError.filter((e) => e.sign).length) {
    show('请填写正确的注册信息')
    return
  }
  // TODO: changePwd API
  // $store.commit('changePwd', {
  //   info: {
  //     newpwd: inputs.newpwd,
  //     verification: inputs.verification,
  //     account: inputs.account,
  //   },
  //   callback: (success) => {
  //     success && $emit('exit')
  //   },
  // })
  // $refs.submitBtn.disabled = true
}

function checkFormat(key: string) {
  switch (key) {
    case 'newpwd':
      !checkPasswordConfirm(inputs.newpwd, inputs.newpwdConfirm) &&
        checkPassword(inputs.newpwd)
      break
    case 'newpwdConfirm':
      !checkPasswordConfirm(inputs.newpwd, inputs.newpwdConfirm) &&
        checkPassword(inputs.newpwd)
      break
    case 'account':
      checkAccount(inputs.account)
      break
  }
}
</script>

<style scoped lang="scss">
$w: var(--userFindpwdWidth);
$fs: calc(var(--userFindpwdWidth) * 0.05);
$ifs: calc($fs * 0.8);
$iw: calc($w * 0.7);

.user-regis-card-wrapper {
  box-sizing: border-box;
  position: relative;
  width: $w;
  padding: calc($w * 0.1) calc(($w - $iw) / 2);
  background-color: white;
  border-radius: calc($w * 0.02);
  text-align: center;

  .icon-cancel {
    right: 0;

    &:hover {
      transform: rotate(180deg);
    }
  }

  .back-to-login {
    left: 0;

    &:hover {
      color: var(--darkBlue);
    }
  }

  .icon-cancel,
  .back-to-login {
    --a: 3vw;
    position: absolute;
    top: 0;
    display: block;
    width: var(--a);
    height: var(--a);
    line-height: var(--a);
    text-align: center;
    font-size: 1.2vw;
    font-weight: bold;
    color: var(--black);
    transition: 0.5s;

    &:hover {
      cursor: pointer;
    }
  }

  h2 {
    font-size: calc($fs * 1.5);
    color: var(--blue);
    line-height: 2;
  }

  .input-info-list {
    width: $iw;

    li {
      position: relative;
      margin-bottom: calc($w * 0.07);
      width: $iw;
      font-size: $fs;

      .info-input {
        --baseInputWidth: $iw;
        --baseInputHeight: calc($fs * 2);
        --baseInputFontsize: $ifs;
        --passwordInputWidth: $iw;
        --passwordInputHeight: calc($fs * 2);
        --passwordInputFontsize: $ifs;
      }

      .signal {
        position: absolute;
        left: 105%;
        top: 0;
        text-align: center;
        font-size: calc($fs * 1.3);
        color: var(--red);
      }

      .sig-message {
        margin-top: calc($fs * 0.4);
        line-height: $fs;
        margin-bottom: calc(-0.7 * $fs);
        padding: 0 calc($fs / 2);
        text-align: left;
        font-size: calc($fs * 0.2);
        color: var(--red);
      }
    }
  }

  .verification {
    margin-bottom: $fs;
    width: $iw;
    height: calc($fs * 2);
    display: flex;
    justify-content: space-between;
    align-items: center;

    .veri-input {
      --baseInputWidth: calc($iw / 2);
      --baseInputHeight: calc($fs * 2);
      --baseInputFontsize: $ifs;
    }

    .send-veri {
      width: 40%;
      height: 100%;
      text-align: center;
      border-radius: calc($fs * 0.3);
      border: 1px solid var(--gray);
      color: var(--dark);
      font-size: $ifs;
      transition: 0.3s;

      &.sendDisable {
        color: var(--gray);
      }

      &:hover {
        cursor: default;
      }

      &.sendAble:hover {
        cursor: pointer;
        border-color: var(--lightBlue);
        color: var(--darkBlue);
      }
    }
  }

  .regis-button {
    width: $iw;
    line-height: 2;
    font-size: calc($fs * 1.2);
    color: white;
    font-weight: bold;
    border-radius: 1.5vw;
    background-image: linear-gradient(-200deg, #fac0e7, #91baff);
  }

  .register-entry {
    margin: calc($fs * 0.5) 0;
    font-size: calc($fs * 0.5);

    span {
      color: var(--blue);

      &:hover {
        cursor: pointer;
      }
    }
  }
}
</style>
